<template>
  <basic-container>
    <div class="container-body">
      <el-form :inline="true" :model="query" class="demo-form-inline">
        <el-row>
          <el-form-item label="年度">
            <el-date-picker placement="bottom-start" v-model="query.planHeadYear" type="year" value-format="yyyy" placeholder="选择年度">
            </el-date-picker>
          </el-form-item>
        </el-row>
        <el-row>
          <el-form-item>
            <el-button size="small" type="primary" icon="el-icon-search" @click="onSearch" :loading="loading">搜索
            </el-button>
            <el-button size="small" icon="el-icon-delete" @click="searchReset" :loading="loading">清空</el-button>
          </el-form-item>
        </el-row>
      </el-form>
      <div class="btn-operate">
        <el-button @click="showAddView()" type="primary" size="small" icon="el-icon-plus">
          年度计划
        </el-button>
      </div>
      <el-table header-row-class-name="container-table-header" :data="data" size="small" style="width: 100%;margin-bottom: 20px;"
                highlight-current-row @cell-click="handleCellClick"
                row-key="id" border stripe v-loading="loading">
        <el-table-column prop="planHeadYear" label="年度" width="80">
        </el-table-column>
        <el-table-column prop="title" label="计划名称">
        </el-table-column>
        <el-table-column prop="planCount" label="计划数">
        </el-table-column>
        <el-table-column prop="projectCount" label="关联项目数">
        </el-table-column>
        <el-table-column prop="auditStatus" label="状态" width="120">
          <template slot-scope="scope">
            <el-tag :type="scope.row.auditStatus | auditStatusTag">{{ scope.row.auditStatus | auditStatus }}</el-tag>
          </template>
        </el-table-column>
        <el-table-column label="操作" width="170">
          <template slot-scope="scope">
            <el-button v-if="permissions.plan_head_get" type="text" size="small" icon="el-icon-view" @click="showViewBox(scope.row)">查看</el-button>
            <el-button v-if="permissions.plan_head_add && (scope.row.auditStatus === 0 || scope.row.auditStatus === 2)" type="text" size="small" icon="el-icon-edit" @click="showEditBox(scope.row)">编辑</el-button>
            <el-button v-if="scope.row.taskId" type="text" size="small" icon="el-icon-edit" @click="showTaskAuditTaskDialog(scope.row)">审批</el-button>
            <el-button v-if="scope.row.auditStatus > 0" type="text" size="small" icon="el-icon-view" @click="showTaskAuditLogDialog(scope.row)">审批日志</el-button>
          </template>
        </el-table-column>
      </el-table>
      <div class="container-page">
        <el-pagination
          @size-change="sizeChange"
          @current-change="currentChange"
          :current-page="page.current"
          :page-sizes="[10, 20, 30, 40, 50, 100]"
          :page-size="10"
          layout="total, sizes, prev, pager, next, jumper"
          :total="page.total">
        </el-pagination>
      </div>
    </div>

    <el-dialog :title="formTitle" fullscreen custom-class="ledger" :visible.sync="formBox" :close-on-click-modal="!formBox" :append-to-body="true" :before-close="resetForm" width="1200px" top="5vh">
      <el-form ref="optForm" :model="form" label-width="90px">
        <el-row :gutter="10">
          <el-col :span="8">
            <el-form-item label="工作年度:" prop="planHeadYear">
              <el-date-picker placement="bottom-start" v-model="form.planHeadYear" type="year" value-format="yyyy" placeholder="选择年度"></el-date-picker>
            </el-form-item>
          </el-col>
          <el-col :span="8">
            <el-form-item label-width="140px" label="编制人:" prop="compiler">
              {{form.compiler}}
            </el-form-item>
          </el-col>
          <el-col :span="8">
            <el-form-item label="编制日期:" prop="planHeadDate">
              <el-date-picker placement="bottom-start" v-model="form.planHeadDate" type="date" placeholder="选择日期"></el-date-picker>
            </el-form-item>
          </el-col>
        </el-row>
        <div class="title">计划明细</div>
        <el-button type="primary" size="mini" icon="el-icon-plus" @click="planDetailAdd(form.plans, true)">增加</el-button>
        <div v-for="(item, idx) in form.plans" :key="idx" style="margin: 20px 0">
          <el-row>
            <el-col :span="8">
              <el-form-item label-width="100px" label="计划名称:" :prop="`plans.${idx}.planName`" :rules="{required: true, message: '计划名称不能为空', trigger: ['blur', 'change']}">
                <el-input v-model="item.planName" placeholder="计划名称"></el-input>
              </el-form-item>
            </el-col>
            <el-col :span="8">
              <el-form-item label-width="100px" label="审计类型:" :prop="`plans.${idx}.auditType`" :rules="{required: true, message: '审计类型不能为空', trigger: ['blur', 'change']}">
                <el-select v-model="item.auditType">
                  <el-option v-for="dict in dict.type.audit_type" v-if="dict.value !== '0'" :key="dict.value" :label="dict.label" :value="parseInt(dict.value)"></el-option>
                </el-select>
              </el-form-item>
            </el-col>
          </el-row>
          <el-row>
            <el-col :span="8">
              <el-form-item label-width="100px" label="被审计单位:" :prop="`plans.${idx}.auditedCompanyName`" :rules="{required: true, message: '被审计单位不能为空', trigger: ['blur', 'change']}">
                <el-input v-model="item.auditedCompanyName" @focus="showTransferDialog(['auditedCompanyId','auditedCompanyName'], 'company', false, idx)" :readonly="true"></el-input>
              </el-form-item>
            </el-col>
            <el-col :span="16">
              <el-form-item label-width="100px" label="审计区间:" :prop="`plans.${idx}.auditDates`">
                <el-date-picker placement="bottom-start" v-model="item.auditDates" type="daterange" unlink-panels range-separator="至" start-placeholder="开始日期" end-placeholder="结束日期"></el-date-picker>
              </el-form-item>
            </el-col>
          </el-row>
          <el-row>
            <el-col :span="8">
              <el-form-item label-width="100px" label="被审计个人:">
                <el-input v-model="item.auditedUserNames" @focus="showTransferDialog(['auditedUserIds','auditedUserNames'], 'auditedUser', false, idx)" :readonly="true"></el-input>
              </el-form-item>
            </el-col>
            <el-col :span="16">
              <el-form-item label-width="100px" label="计划时间:" :prop="`plans.${idx}.planDates`">
                <el-date-picker placement="bottom-start" v-model="item.planDates" type="daterange" unlink-panels range-separator="至" start-placeholder="开始日期" end-placeholder="结束日期"></el-date-picker>
              </el-form-item>
            </el-col>
          </el-row>
          <el-row type="flex" justify="center" v-if="form.plans.length > 1"><el-button type="danger" size="mini" @click="planDetailDel(idx)">删除</el-button></el-row>
        </div>
      </el-form>
      <span slot="footer" class="dialog-footer">
        <el-button @click="resetForm(form)" size="small" icon="el-icon-close">关闭</el-button>
        <el-button type="primary" @click="submit" size="small" icon="el-icon-check">保存</el-button>
        <el-button type="primary" @click="submitAudit" size="small" icon="el-icon-check">保存送审</el-button>
      </span>
    </el-dialog>

    <el-dialog top="5vh" :title="formTitle" :visible.sync="viewBox"
               :append-to-body="true" :before-close="closeViewBox" width="1000px">
      <PlanHeadAuditView :params="form"></PlanHeadAuditView>
      <span slot="footer" class="dialog-footer">
        <el-button @click="closeViewBox" size="small" icon="el-icon-close">关闭</el-button>
      </span>
    </el-dialog>

    <FormTransfer :transferDialog="transferDialog" :transferDialogType="transferDialogType" :multiple="transferDialogMultiple" @transferData="transferDataHandle" @closeTransfer="closeTransfer" :transferCurrent="transferCurrent" />
    <TaskAuditDialog :dialog="taskAuditDialog" @setValue="setTaskAuditTaskDialog" @closeDialog="closeTaskAuditTaskDialog" ref="taskAuditDialog" />
    <TaskAuditLogDialog :dialog="taskAuditLogDialog" :process-id="processId" @closeDialog="closeTaskAuditTaskLogDialog"/>
  </basic-container>
</template>

<script>
import {mapGetters} from "vuex";
import Tinymce from '@/components/Tinymce'
import {listPlanHeadYear} from "@/api/adis/work/plan";
import {auditPass, delObj, fetchList, getObj, submit, submitAudit} from "@/api/adis/work/planHead";
import FormTransfer from "@/components/form/transfer";
import TaskAuditDialog from "@/components/act/TaskAuditDialog";
import TaskAuditLogDialog from "@/components/act/TaskAuditLogDialog";
import PlanHeadAuditView from "@/components/actForm/PlanHeadAuditView";

export default {
  directives: {
  },
  components: {
    PlanHeadAuditView,
    Tinymce,
    FormTransfer,
    TaskAuditDialog,
    TaskAuditLogDialog,
  },
  dictTypes: ['audit_type'],
  data() {
    return {
      importBox: false,
      viewBox: false,
      formBox: false,
      formTitle: '',
      loading: false,
      query: {},
      form: {
        plans: [
          {
            auditType:1
          }
        ],
      },
      page: {
        size: 10,
        current: 1,
        total: 0
      },
      data: [],
      selectionRow: [],
      Authorization: '',
      fileList: [], // 文件

      transferDialog: false,
      transferDialogType: '',
      transferDialogArr: [],
      transferDialogMultiple: false,
      planIndex: 0,
      planHeadYears: [],
      transferCurrent: {},

      taskAuditDialog: false,
      taskAuditLogDialog: false,
      processId: ''
    }
  },
  watch: {
    form:{
      handler(val){
        if (val.planHeadYear){
          this.formTitle = val.planHeadYear + '年度审计计划';
        }
      },immediate: true, deep: true,
    },
  },
  computed: {
    ...mapGetters(["permissions", "userInfo"])
  },
  created() {
    this.onLoad(this.page);
    this.Authorization = 'Bearer ' + this.$store.getters.access_token
  },
  methods: {
    handleCellClick(row, column) {
      if (row && column.label !== "操作"){
        this.showViewBox(row)
      }
    },

    // 获取所有已经审批通过的年度计划年度
    listPlanHeadYear(){
      listPlanHeadYear().then((res) => {
        this.$set(this,"planHeadYears", res.data.data)
      });
    },

    submit() {
      this.$refs['optForm'].validate((valid) => {
        if (this.planHeadYears.includes(Number(this.form.planHeadYear))){
          this.$message({
            type: "warning",
            message: "已有该年度计划，请重新输入!"
          });
          return false;
        }
        if (valid) {
          this.fileList && this.fileList.map((file) => {
            this.form.fileUrl = file.response ? file.response.data.url : file.url
          });
          for(let item of this.form.plans) {
            if(item.auditDates) {
              item.auditStartDate = item.auditDates[0];
              item.auditEndDate = item.auditDates[1];
            }
            if(item.planDates) {
              item.planStartDate = item.planDates[0];
              item.planEndDate = item.planDates[1];
            }
          }
          this.loading = true;
          submit(this.form).then(() => {
            this.$message({
              type: "success",
              message: "操作成功!"
            });
            this.resetForm();
            this.onLoad(this.page);
          }, () => {
            this.loading = false;
          });
        } else {
          return false;
        }
      });
    },
    submitAudit() {
      this.$refs['optForm'].validate((valid) => {
        if (valid) {
          this.fileList && this.fileList.map((file) => {
            this.form.fileUrl = file.response ? file.response.data.url : file.url
          });
          for(let item of this.form.plans) {
            if(item.auditDates) {
              item.auditStartDate = item.auditDates[0];
              item.auditEndDate = item.auditDates[1];
            }
            if(item.planDates) {
              item.planStartDate = item.planDates[0];
              item.planEndDate = item.planDates[1];
            }
          }
          this.loading = true;
          submitAudit(this.form).then(() => {
            this.$message({
              type: "success",
              message: "操作成功!"
            });
            this.resetForm();
            this.onLoad(this.page);
          }, () => {
            this.loading = false;
          });
        } else {
          return false;
        }
      });
    },
    auditPass(form) {
      this.$confirm("确定要审批通过吗?", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning"
      }).then(() => {
        return auditPass(form.planHeadId);
      })
        .then(() => {
          this.onLoad(this.page);
          this.$message({
            type: "success",
            message: "操作成功!"
          });
        });
    },
    auditReject(form) {
      this.$confirm("确定要驳回审批吗?", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning"
      }).then(() => {
        return auditReject(form.planHeadId);
      })
        .then(() => {
          this.onLoad(this.page);
          this.$message({
            type: "success",
            message: "操作成功!"
          });
        });
    },
    showAddView() {
      getObj(0).then((res) => {
        this.form = res.data.data;
        this.form.planHeadYear = this.form.planHeadYear + ''
        if (!this.form.plans.length) {
          this.form.plans = [{ chargeType: 2 }];
        }
        if (res.data.data.fileUrl) {
          this.fileList.push({url:res.data.data.fileUrl});
        }
        if (!this.form.compilerId && !this.form.compiler && this.form.auditStatus === 5) {
          this.form.compilerId = this.userInfo.userId;
          this.form.compiler = this.userInfo.realname;
        }
        for(let item of this.form.plans) {
          if(item.auditStartDate && item.auditEndDate) {
            this.$set(item, "auditDates", [item.auditStartDate, item.auditEndDate]);
          }
          if(item.planStartDate && item.planEndDate) {
            this.$set(item, "planDates", [item.planStartDate, item.planEndDate]);
          }
        }
        this.formTitle = '年度审计计划';
        this.formBox = true;
      });
    },
    showEditBox(row) {
      getObj(row.planHeadId).then((res) => {
        this.form = res.data.data;
        this.form.planHeadYear = this.form.planHeadYear + ''
        if(res.data.data.fileUrl) {
          this.fileList.push({url:res.data.data.fileUrl});
        }
        for(let item of this.form.plans) {
          if(item.auditStartDate && item.auditEndDate) {
            this.$set(item, "auditDates", [item.auditStartDate, item.auditEndDate]);
          }
          if(item.planStartDate && item.planEndDate) {
            this.$set(item, "planDates", [item.planStartDate, item.planEndDate]);
          }
        }
        this.formTitle = row.title;
        this.formBox = true;
      });
    },
    showViewBox(row) {
      getObj(row.planHeadId).then((res) => {
        this.form = res.data.data;
        this.form.planHeadYear = this.form.planHeadYear + ''
        this.formTitle = row.title;
        this.viewBox = true;
      });
    },
    closeViewBox() {
      this.viewBox = false;
    },
    handleDelete(row) {
      this.$confirm("确定将选择的数据删除?", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning"
      }).then(() => {
        return delObj(row.renterId);
      })
        .then(() => {
          this.onLoad(this.page);
          this.$message({
            type: "success",
            message: "操作成功!"
          });
        });
    },
    resetForm(form) {
      if (form && form.auditStatus > 4) {
        delObj(form.planHeadId)
      }
      this.formBox = false;
      this.viewBox = false;
      this.form = {
        plans: [
          {
            auditType:1
          }
        ],
      };
      this.formTitle = '';
      this.$refs['optForm'] && this.$refs['optForm'].resetFields();
      this.viewBox = false;
      this.printBox = false;
      this.onLoad(this.page);
    },
    onSearch() {
      this.page.current = 1;
      this.onLoad(this.page);
    },
    searchReset() {
      this.query = {};
      this.page.current = 1;
      this.onLoad(this.page);
    },
    currentChange(current) {
      this.page.current = current;
      this.onLoad(this.page);
    },
    sizeChange(size) {
      this.page.size = size;
      this.onLoad(this.page);
    },
    onLoad(page, params = {}) {
      this.loading = true;
      if(this.query.publishDates) {
        this.query.startDate = this.query.publishDates[0];
        this.query.endDate = this.query.publishDates[1];
      }
      fetchList(Object.assign(params, this.query, page)).then(res => {
        this.loading = false;
        const data = res.data.data;
        this.page.total = data.total;
        this.data = data.records;
        this.listPlanHeadYear()
      }, () => {
        this.loading = false;
      });
    },
    handleRemove(file, fileList) {
      this.fileList = fileList
    },
    handleSuccess(response, file, fileList) {
      this.fileList = fileList;
    },
    handlePreview(file) {
      window.open(file.url ? file.url : file.response.data.url)
    },
    beforeRemove(file) {
      return this.$confirm(`确定移除 ${file.name}？`);
    },

    // 增加计划明细
    planDetailAdd(row) {
      row.push({chargeType:2})
    },
    // 删除计划明细
    planDetailDel(index) {
      this.form.plans.splice(index, 1);
    },

    // 审计对象选择
    showTransferDialog(transferDialogArr, transferDialogType, transferDialogMultiple, planIndex) {
      this.transferDialogArr = transferDialogArr; // 表单字段
      this.transferDialogType = transferDialogType; // 判断类型user:人员，unit:职位，department:部门,company:单位,plan:计划等
      this.transferDialogMultiple = transferDialogMultiple; // 是否多选
      this.planIndex = planIndex; // 表单循环当前数组
      if (transferDialogType === 'company') {
        this.transferCurrent.type = 2;
      }
      if (transferDialogType === 'user') {
        if(!this.form.plans[planIndex].auditedCompanyId) {
          this.$message({
            type: "warning",
            message: "请先选择单位!"
          });
          return
        }
        this.transferCurrent.deptId = this.form.plans[planIndex].auditedCompanyId;
      }
      //重组数组name和id
      this.transferCurrent.currentval = []
      if(this.form.plans[planIndex][this.transferDialogArr[0]]) {
        if (this.form.plans[planIndex][this.transferDialogArr[0]].indexOf(',') > -1) {
          this.form.plans[planIndex][this.transferDialogArr[0]].split(',').forEach((item, i) => {
            this.transferCurrent.currentval.push({name: this.form.plans[planIndex][this.transferDialogArr[1]].split(',')[i], id: item})
          })
        }  else {
          this.transferCurrent.currentval = [{name: this.form.plans[planIndex][this.transferDialogArr[1]], id: this.form.plans[planIndex][this.transferDialogArr[0]]}]
        }
      }
      this.transferDialog = true;
    },
    transferDataHandle(e) {
      console.log(e, '返回')
      this.transferDialog = false
      let currentId = [], currentName = []
      if (e.list.length > 1) {
        e.list.forEach(item => {
          currentId.push(item.id)
          currentName.push(item.name)
        })
      }
      if (e.list.length === 1) {
        currentId = [e.list[0].id]
        currentName = [e.list[0].name]
      }
      let currentIdStr = currentId.length > 0 ? currentId.join(',') : null
      let currentNameStr = currentName.length > 0 ? currentName.join(',') : null
      if (currentIdStr && currentIdStr.substring(0, 1) === ',') currentIdStr.slice(1);
      if (currentNameStr && currentNameStr.substring(0, 1) === ',') currentNameStr.slice(1);
      this.$set(this.form.plans[this.planIndex], this.transferDialogArr[0], currentIdStr)
      this.$set(this.form.plans[this.planIndex], this.transferDialogArr[1], currentNameStr)
    },
    closeTransfer() {
      this.transferDialog = false;
    },

    /**=========审批相关==begin===========*/
    showTaskAuditTaskDialog(row) {
      this.taskAuditDialog = true;
      this.$refs['taskAuditDialog'].initData({taskId: row.taskId, processId: row.processId});
    },
    closeTaskAuditTaskDialog() {
      this.taskAuditDialog = false;
    },
    setTaskAuditTaskDialog() {
      this.taskAuditDialog = false;
      this.onLoad(this.page);
    },
    showTaskAuditLogDialog(row) {
      this.processId = row.processId;
      this.taskAuditLogDialog = true;
    },
    closeTaskAuditTaskLogDialog() {
      this.taskAuditLogDialog = false;
    },
    /**=========审批相关==end===========*/
  }
};
</script>

<style>
</style>
